package cn.wen.javax.xml.oxm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

import cn.wen.java.io.HelperOfIO;

/**
 * Title: Castor OXM
 * <p>
 * Description: Java 序列化相关的辅助类，主要功能：编组（Object => Xml），解组（Object <= Xml）。
 * <p>
 * Copyright: Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision: 1.0 Date: 2011/2/23 description：初完成。
 *          </P>
 * 
 */
public class HelperOfCastor {

    // -----------------------------------------------------------------------
    // Marshal
    // -----------------------------------------------------------------------
    /**
     * 利用Spring 将对象 进行编组。
     * 
     * @param o 对象
     * @param path 路径
     * @throws IOException
     * @throws XmlMappingException
     */
    public static void marshalOfCastor(Object o, String path) throws XmlMappingException, IOException {
	OutputStream os = null;
	try {
	    os = new FileOutputStream(path);
	    getMarshaller().marshal(o, new StreamResult(os));
	}
	finally {
	    HelperOfIO.closes(os);
	}
    }

    // -----------------------------------------------------------------------
    // Unmarshal
    // -----------------------------------------------------------------------

    /**
     * 利用Spring 对文件进行 解组，并返回文件解组后的对象。
     * 
     * @param path 路径
     * @param T 类型
     * @return 对象
     * @throws IOException
     * @throws XmlMappingException
     */
    public static <T> T unMarshalOfCastor(String path, Class<T> T) throws XmlMappingException, IOException {
	InputStream is = null;
	try {
	    is = new FileInputStream(path);
	    return (T) getUnmarshaller().unmarshal(new StreamSource(is));
	}
	finally {
	    HelperOfIO.closes(is);
	}
    }

    private static Marshaller marshaller;

    private static Unmarshaller unmarshaller;

    public static Marshaller getMarshaller() {
	return marshaller;
    }

    public void setMarshaller(Marshaller marshaller) {
	HelperOfCastor.marshaller = marshaller;
    }

    public static Unmarshaller getUnmarshaller() {
	return unmarshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
	HelperOfCastor.unmarshaller = unmarshaller;
    }

}
